package com.luguangxing.controller;

import com.luguangxing.entity.StatusEntity;
import com.luguangxing.service.AliyunMessageService;
import com.luguangxing.service.JunkMailService;
import com.luguangxing.service.UserService;
import com.luguangxing.utils.CommUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: 小白一号
 * @date: 2022/11/18
 * @desc:
 */
@Slf4j
@RestController
@RequestMapping("/verifyCode")
public class VerifyCode {
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private AliyunMessageService aliyunMessageService;
    @Autowired
    private JunkMailService junkMailService;
    @Autowired
    private UserService userService;

    /**
     * 根据手机生成用于注册账号的验证码，生成验证码之前会判断用户是否存在
     * 该接口用于注册用户，因为当用户不存在时才会下发验证码，而不是存在就下发
     *
     * @param map userPhone
     * @return
     * @throws Exception
     */
    @PostMapping("/createRegisterPhoneVerify")
    public Object createRegisterPhoneVerify(@RequestBody Map<String, Object> map) throws Exception {
        StatusEntity status = new StatusEntity();
        try {
            if (userService.findByUserPhone(map.get("userPhone").toString()) != null) {
                status.setStatus("userExist");
                status.setCode("302");
            } else {  // 手机号未注册过，可以下发验证码
                String verifyCode = CommUtils.randomVeryCode();
                if (aliyunMessageService.sendVerifyCode(map.get("userPhone").toString(), verifyCode)) {
                    status = new StatusEntity("success", "200");
                } else {
                    status = new StatusEntity("error", "302");
                }
            }
        } catch (Exception e) {
        }
        return status;
    }

    /**
     * 根据邮箱生成用于注册账号的验证码，生成验证码之前会判断用户是否存在
     *
     * @param map userEmail
     * @return
     * @throws Exception
     */
    @PostMapping("/createRegisterEmailVerify")
    public Object createRegisterEmailVerify(@RequestBody Map<String, Object> map) throws Exception {
        StatusEntity status = new StatusEntity();
        try {
            if (userService.findByUserEmail(map.get("userEmail").toString()) != null) {
                status.setStatus("userExist");
                status.setCode("302");
            } else {  // 邮箱未注册过，可以下发验证码
                String verifyCode = CommUtils.randomVeryCode();
                if (junkMailService.sendVerifyCode(map.get("userEmail").toString(), verifyCode)) {
                    status = new StatusEntity("success", "200");
                } else {
                    status = new StatusEntity("error", "302");
                }
            }
        } catch (Exception e) {
            log.info(e.toString());
        }
        return status;
    }

    /**
     * 根据手机号生成验证码，用于验证码登录或找回密码
     *
     * @param map userPhone
     * @return
     * @throws Exception
     */
    @PostMapping("/createPhoneVerify")
    public Object phoneVirifyCode(@RequestBody Map<String, Object> map) throws Exception {
        StatusEntity status = new StatusEntity();
        try {
            // 用户是否存在
            if (userService.findByUserPhone(map.get("userPhone").toString()) == null) {
                status.setStatus("userNotExist");
                status.setCode("302");
            } else {  // 手机号注册过（用户存在），可以下发验证码
                String verifyCode = CommUtils.randomVeryCode();
                if (aliyunMessageService.sendVerifyCode(map.get("userPhone").toString(), verifyCode)) {
                    status = new StatusEntity("success", "200");
                } else {
                    status = new StatusEntity("error", "302");
                }
            }
        } catch (Exception e) {
        }
        return status;
    }

    /**
     * 根据生成邮箱验证码，用于用户验证码登录或找回密码
     *
     * @param map userEmail
     * @return
     * @throws Exception
     */
    @PostMapping("/createEmailVerify")
    public Object emailVirifyCode(@RequestBody Map<String, Object> map) throws Exception {
        StatusEntity status = new StatusEntity();
        try {
            if (userService.findByUserEmail(map.get("userEmail").toString()) == null) {
                status.setStatus("userNoExist");
                status.setCode("302");
            } else {  // 用户存在，可以下发验证码
                String verifyCode = CommUtils.randomVeryCode();
                if (junkMailService.sendVerifyCode(map.get("userEmail").toString(), verifyCode)) {
                    status = new StatusEntity("success", "200");
                } else {
                    status = new StatusEntity("error", "302");
                }
            }
        } catch (Exception e) {
        }
        return status;
    }

    /**
     * 验证码比对
     */
    @PostMapping("/verifyCode")
    public Object verifyCode(@RequestBody Map<String, Object> map) {
        StatusEntity status;
        try {
            String phoneOrEmail = map.get("phoneOrEmail").toString();
            String code = map.get("code").toString();
            // 从Redis中取出验证码
            String codeFromRedis = redisTemplate.opsForValue().get(phoneOrEmail).toString();
            if (codeFromRedis != null) {
                if (codeFromRedis.equals(code)) {
                    status = new StatusEntity("success", "200");
                } else {
                    status = new StatusEntity("error", "302");
                }
            } else {
                status = new StatusEntity("empty", "301");
            }
        } catch (Exception e) {
            status = new StatusEntity("paramError", "303");
        }
        return status;
    }
}
